#pragma once

#include <iostream>
#include <unistd.h>
#include <string>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "log.hpp"

Log lg;
const int backlog = 10;

enum
{
    SockError = 2,
    BindError,
    ListenError,

};

class Sock
{
public:
    Sock()
    {}
    ~Sock()
    {}

    void Socket()
    {
        sockfd_ = socket(AF_INET,SOCK_STREAM, 0);
        if(sockfd_ < 0)
        {
            lg(Fatal, "socket error, errno : %d , errstr : %s", errno, strerror(errno));
            exit(SockError);
        }
    }

    void Bind(uint16_t port)
    {
        //创建套接字结构体，并填写信息
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = PF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;

        if(bind(sockfd_, (struct sockaddr*)&local, (socklen_t)sizeof(local)) < 0)
        {
            lg(Fatal, "bind error, errno : %d , errstr : %s", errno, strerror(errno));
            exit(BindError);
        }
    }

    void Listen()
    {
        if(listen(sockfd_,backlog) < 0)
        {
            lg(Fatal, "listen error, errno : %d , errstr : %s", errno, strerror(errno));
            exit(ListenError);
        }
    }

    int Accept(std::string *clientip, uint16_t* clientport)
    {
        struct sockaddr_in peer;//远端套接字信息
        socklen_t len = sizeof(peer);
        int newfd = accept(sockfd_,(struct sockaddr*)&peer, &len);
        if(newfd < 0)
        {
            lg(Warning, "accept error, errno : %d , errstr : %s", errno, strerror(errno));
            return -1;
        }
        char ipstr[64];
        inet_ntop(AF_INET, &peer.sin_addr, ipstr, sizeof(ipstr));
        *clientip = ipstr;
        *clientport = ntohs(peer.sin_port);
        return newfd;
    }

    void Close()
    {
        close(sockfd_);
    }
 
    bool Connect(const std::string& ip, const int16_t& port)
    {
        struct sockaddr_in peer;
        memset(&peer,0 ,sizeof(peer));
        peer.sin_family = AF_INET;
        peer.sin_port = htons (port);
        inet_pton(sockfd_, ip.c_str(), &(peer.sin_addr)); 
        int n = connect(sockfd_, (const struct sockaddr*)&peer, (socklen_t)sizeof(peer));
        if(n == -1)
        {
            std::cerr << "connect to "  << ip << ":" << port << std::endl;
            return false; 
        }
        return true;
    }

    int Fd()
    {
        return sockfd_;
    }
private:
    int sockfd_;
};